# -*- coding: utf-8 -*-
# __author__ = 'xxx'
# env: python 2.7  requests 2.27.1
# fuction:  基本 认证

import  urllib2
import requests

def baseauth():

    # 进行基本验证的服务器
    openurl="http://127.0.0.1/status"
    foropen=urllib2.Request(openurl)
    
    # 封装 header
    #添加认证 帐号ii密码   user:pass  ,base64 加密 帐号密码
    foropen.add_header("Authorization", "Basic YWRtaW46dGVzdDEyMw==")
    foropen.add_header("User-Agent","curl/7.74.0 ")
    
    opensite=urllib2.urlopen(foropen)
    
    #打印响应
    print(opensite.read())


def baseauthhandler():

    # 参考帮助手册例子
    auth=urllib2.HTTPBasicAuthHandler()
    
    #由于遵循严格的验证模型，所以  注意  realm 要和 验证段 保持一致
    auth.add_password(realm="Access to the staging site", uri='http://127.0.0.1/status',user='admin',passwd='test123')
    
    opensite2=urllib2.build_opener(auth)
    urllib2.install_opener(opensite2)
    
    oc=urllib2.urlopen("http://127.0.0.1/status")
    
    print(oc.read())
    
    

def baseauthrequests():
        
    
    #authreq = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
    authreq=requests.get('http://127.0.0.1/status', auth=('admin', 'test123'))
    print("使用 requests 进行认证")
    print(authreq.content)
    

baseauth()

baseauthhandler()

baseauthrequests()
